#!/usr/bin/env bash
set -e
set -u
set -o pipefail


get_absolute_path() {
    local path=${1:-}
    if [ -d "$path" ]; then
        # shellcheck disable=SC2005
        echo "$(cd "${path}" && pwd || echo "")"
    elif [ -f "$path" ]; then
        # shellcheck disable=SC2005
        echo "$(cd "$(dirname "${path}")" && echo "$(pwd)"/"$(basename "${path}")" || echo "")"
    elif [ -z "$path" ]; then
        >&2 echo "WARNING: ${FUNCNAME[0]}: empty path"
        echo ""
    else
        >&2 echo "ERROR: ${FUNCNAME[0]}: cannot find file or directory: \"${path}\""
        echo ""
    fi
}


get_absolute_path_main() {
    local beg_dir=${1:?}


    echo "These should pass:"
    test "$(get_absolute_path "/")" == "/" || \
        echo "root path failed"
    test "$(get_absolute_path ".")" == "$(pwd)" || \
        echo "current directory failed"
    test "$(get_absolute_path "..")" == "$(dirname "$(pwd)")" || \
        echo "parent directory failed"
    test "$(get_absolute_path "./get_absolute_path")" == "$(pwd)/get_absolute_path" || \
        echo "path to this file failed"
    test "$(get_absolute_path "./README.org")" == "$(pwd)/README.org" || \
        echo "path to sibling file failed"


    echo ""
    echo "These should fail to stderr, but not fail the tests:"
    test "$(get_absolute_path)" == "" || echo "no input failed"
    test "$(get_absolute_path "")" == "" || echo "empty string failed"
    test "$(get_absolute_path "/probably_no_such_path")" == "" || echo "bad path failed"


    if [[ "$beg_dir" != "$(pwd)" ]]; then
        echo "WARNING: We changed directories"
    fi
}


get_absolute_path_main "$(pwd)"
